<template>
  <div
    :style="{ width: width + 'px' }"
    class="tinymce-container editor-container"
  >
    <textarea class="tinymce-textarea" :id="tinymceId"></textarea>
    <div class="editor-custom-btn-container">
      <editorImage
        color="#1890ff"
        class="editor-upload-btn"
        @successCBK="imageSuccessCBK"
        type="2"
      ></editorImage>
    </div>
  </div>
</template>

<script>
import editorImage from "./components/editorImage";
import "../../../static/tinymce/langs/zh_CN";

const plugins = [
  "code letterspacing print preview searchreplace autolink directionality visualblocks visualchars fullscreen image link media template code codesample table charmap hr pagebreak nonbreaking anchor insertdatetime advlist lists wordcount imagetools textpattern help emoticons autosave bdmap indent2em autoresize formatpainter axupimgs"
];

const toolbar = [
  "code lineheight letterspacing undo redo restoredraft | cut copy paste pastetext | forecolor backcolor bold italic underline strikethrough link anchor | alignleft aligncenter alignright alignjustify outdent indent | \
    styleselect  fontselect fontsizeselect | bullist numlist | blockquote subscript superscript removeformat | \
    table image media charmap emoticons hr pagebreak insertdatetime print preview | fullscreen | bdmap indent2em formatpainter axupimgs"
];
export default {
  name: "tinymce",
  components: { editorImage },
  props: {
    id: {
      type: String
    },
    value: {
      type: String,
      default: ""
    },
    toolbar: {
      type: Array,
      required: false,
      default() {
        return [];
      }
    },
    menubar: {
      default: "file edit insert view format table"
    },
    height: {
      type: Number,
      default: 500
    },
    width: {
      type: [Number, String],
      default: 1000
    },
  },
  data() {
    return {
      hasChange: false,
      hasInit: false,
      tinymceId: this.id || "vue-tinymce-" + +new Date(),
      readonly:false
    };
  },
  watch: {
    value(val) {
      if (!this.hasChange && this.hasInit) {
        this.$nextTick(() =>
          window.tinymce.get(this.tinymceId).setContent(val)
        );
      }
    }
  },
  mounted() {
    this.initTinymce();
  },
  activated() {
    this.initTinymce();
  },
  deactivated() {
    this.destroyTinymce();
  },
  methods: {
    setRead(is) {
      this.readonly = is;
      this.$nextTick(() => {
        window.tinymce.get(this.tinymceId).setMode(is ? "readonly" : "design");
      });
    },
    initTinymce() {
      const _this = this;
      window.tinymce.init({
        language: "zh_CN",
        selector: `#${this.tinymceId}`,
        height: this.height,
        min_height: 400,
        body_class: "panel-body ",
        object_resizing: false,
        toolbar: this.toolbar.length > 0 ? this.toolbar : toolbar,
        menubar: this.menubar,
        plugins: plugins,
        readonly: this.readonly,
        end_container_on_empty_block: true,
        powerpaste_word_import: "clean",
        code_dialog_height: 450,
        code_dialog_width: 1000,
        advlist_bullet_styles: "square",
        advlist_number_styles: "default",
        imagetools_cors_hosts: ["www.tinymce.com", "codepen.io"],
        default_link_target: "_blank",
        link_title: false,
        lineheight_formats: "1 1.5 2 2.5 3 3.5 4 4.5 5 6 7 8 9",
        convert_urls: false, //防止路径被转化为相对路径
        nonbreaking_force_tab: true, // inserting nonbreaking space &nbsp; need Nonbreaking Space Plugin
        init_instance_callback: editor => {
          if (_this.value) {
            editor.setContent(_this.value);
          }
          _this.hasInit = true;
          editor.on("NodeChange Change KeyUp SetContent", () => {
            this.hasChange = true;
            this.$emit("input", editor.getContent());
          });
          // Add listener for fullscreen mode change
          editor.on("FullscreenStateChanged", e => {
            const editorContainer = document.querySelector(
              ".tinymce-container.editor-container"
            );
            if (editorContainer) {
              if (e.state) {
                editorContainer.classList.add("fullscreen"); // Add class when entering fullscreen mode
              } else {
                editorContainer.classList.remove("fullscreen"); // Remove class when exiting fullscreen mode
              }
            }
          });
        }
      });
    },
    destroyTinymce() {
      if (window.tinymce.get(this.tinymceId)) {
        window.tinymce.get(this.tinymceId).destroy();
      }
    },
    setContent(value) {
      window.tinymce.get(this.tinymceId).setContent(value);
    },
    getContent() {
      window.tinymce.get(this.tinymceId).getContent();
    },
    imageSuccessCBK(arr) {
      const _this = this;
      arr.forEach(v => {
        window.tinymce
          .get(_this.tinymceId)
          .insertContent(`<div><img class="wscnph" src="${v.url}" ></div>`);
      });
    }
  },
  destroyed() {
    this.destroyTinymce();
  }
};
</script>

<style scoped>
.fullscreen {
  margin-left: 30px;
}
.tinymce-container {
  /* width: 1000px; */
  position: relative;
  line-height: normal;
}

.tinymce-container >>> .mce-fullscreen {
  z-index: 1000;
}

.tinymce-textarea {
  visibility: hidden;
  z-index: -1;
}
.fullscreen .editor-custom-btn-container {
  position: fixed;
  z-index: 10000;
  right: 4px;
  top: 4px;
}
.editor-custom-btn-container {
  position: absolute;
  right: 4px;
  top: 4px;
  z-index: 100;
}

.editor-upload-btn {
  display: inline-block;
}
</style>
